/*
 * @Author: 徐建辰
 * @Date: 2021-11-04 09:09:44
 * @LastEditTime: 2021-11-04 15:44:28
 * @LastEditors: Please set LastEditors
 * @Description: 城市选择组件
 */
import React, {useState, useMemo, useEffect, memo, useCallback} from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import CityList from './CityList'
import Search from './Search'
import './CitySelector.css'

const CitySelector = memo(function CitySelector(props) {
  const {cityData, show, isLoading, onBack, fetchCityData, onSelect} = props
  const [searchKey, setSearchKey] = useState('')
  const key = useMemo(() => searchKey.trim(), [searchKey])

  useEffect(() => {
    if (!show || cityData || isLoading) return
    fetchCityData()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [show, cityData, isLoading])

  const outputCityData = () => {
    if (isLoading) return <div>loading.....</div>
    if (cityData) return <CityList toAlpha={toAlpha} sections={cityData.cityList} onSelect={onSelect} />
    return <div>错误。。。。。</div>
  }
  // 点击字母到对应位置
  const toAlpha = useCallback(alpha => {
    document.querySelector(`[data-cate=${alpha}]`).scrollIntoView()
  }, [])
  return (
    // 不使用className---》className={['city-selector', (!show) && 'hidden'].filter(Boolean).join(' ')}
    // 使用className  ---》show为false的时候就会追加hidden这个className
    <div className={classNames('city-selector', {hidden: !show})}>
      <div className="city-search">
        <div className="search-back" onClick={() => onBack(false)}>
          <svg width="42" height="42">
            <polyline
              points="25,13 16,21 25,29"
              stroke="#fff"
              strokeWidth="2"
              fill="none"
            />
          </svg>
        </div>
        <div className="search-input-wrapper">
          <input onChange={e => setSearchKey(e.target.value)} type="text" value={searchKey} className="search-input" placeholder="城市、车站的中文" />
        </div>
        <i className={classNames('search-clean', {hidden: !key.length})} onClick={() => setSearchKey('')}>&#xf063;</i>
      </div>
      {Boolean(key) && <Search searchKey={key} onSelect={key => onSelect(key)} />}
      {outputCityData()}
    </div>
  )
})

CitySelector.propTypes = {
  show: PropTypes.bool.isRequired,
  cityData: PropTypes.object,
  isLoading: PropTypes.bool.isRequired,
  onBack: PropTypes.func.isRequired,
  onSelect: PropTypes.func.isRequired,
}

export default CitySelector
